﻿using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;

namespace PicasaMobileInterface
{
   public class BloggerInterface
    {
       AutoResetEvent auto = new AutoResetEvent(false);
       private string _userName = String.Empty;
       private string _password = String.Empty;
       private string _userId = String.Empty;
       private string _token = String.Empty;

       public BloggerInterface(string UserName, string Password)
        {
            _userName = UserName;
            _userId = _userName.Substring(0, _userName.IndexOf("@"));
            CONST.USER = _userId;
            _password = Password;
            Login();
        }
       private string ParseAuthToken(string response)
       {

           string auth = "";
           try
           {
               auth = new Regex(@"Auth=(?<auth>\S+)").Match(response).Result("${auth}");
           }
           catch(Exception ex)
           { 
           }
           CONST.AUTH_BToken = auth;
           return auth;
       }
       private void Login()
       {
           var client = new RestClient(CONST.AUTH_URL);
           var request = new RestRequest(CONST.AUTH_REQ, Method.POST);
           request.AddParameter("service", CONST.AUTH_BSERVICE, ParameterType.GetOrPost);
           request.AddParameter("accountType", CONST.AUTH_ACCOUNTTYPE, ParameterType.GetOrPost);
           request.AddParameter("source", CONST.AUTH_BSOURCE, ParameterType.GetOrPost);
           request.AddParameter("Email", _userName, ParameterType.GetOrPost);
           request.AddParameter("Passwd", _password, ParameterType.GetOrPost);

           try
           {
               client.ExecuteAsync(request, (response) =>
               {
                   _token = ParseAuthToken(response.Content);
                   auto.Set();                 
               });
               auto.WaitOne();

           }
           catch (Exception ex)
           {
               
           }
       }
    }
}
